<template>
  <base-page-view class-name="tab-container b-home-container">
    <view class="bg" :style="'background: #FFF ' + bgStyle">
      <base-nav class-name="bg-nav" :background="bgStyle" background-position=" top center;" other-height="96rpx">
        <view slot="left" class="nav-left click-active">
          <!-- <image class="icon" src="/static/images/icon/icon_return.png" mode="aspectFit" /> -->
          <view>碧划算搜索领券</view>
        </view>
        <view slot="right" class="nav-right click-active" @click="toMine">
          <image class="icon" src="/static/images/icon/icon_order.png" mode="aspectFit" />
        </view>
        <view slot="other" class="search-block" @click="toSearchPage">
          <search-bar placeholder="黏贴商品标题，先领券再购买" text-align="left" disabled></search-bar>
        </view>
      </base-nav>
      <view class="banner-block">
        <base-swiper class-name="banner" :swiper-list="banner_list" border-radius="20rpx" @itemClick="bannerItemClick"></base-swiper>
      </view>
      <view v-if="platform_list && platform_list.length > 1" class="platform-list">
        <view v-for="(item, index) in platform_list" :key="index" class="platform-item" :class="{ active: goodsQuery.platform === item.platform }" @click="platformChange(item)">{{ item.name }}</view>
      </view>
      <view class="sticky-wrap bg-block" :style="'top: ' + (statusBarHeight + 40 + Math.ceil((92 / 750) * screenWidth)) + 'px;'">
        <horizontalList ref="category-list" list-name="category" :click-emit-index="0" :list="catehory_list" @itemClick="categoryItemClick">
          <template v-slot="{ item }">
            <view class="item">{{ item.title }}</view>
          </template>
        </horizontalList>
      </view>
      <view class="goods-block">
        <view v-for="(item, index) in goods_list" :key="index" class="goods-item">
          <view class="goods-item-wrapper" @click="toGoods(item)">
            <view class="goods-img">
              <b-image :src="item.imageUrl" mode="aspectFit" />
            </view>
            <view class="goods-detail">
              <view class="goods-name">
                <view class="platform" :class="'platform-' + goodsQuery.platform">{{ goodsQuery.platformName }}</view>
                {{ item.title }}
              </view>
              <view class="goods-discount">
                <view v-if="item.hasCoupon || item.discount" class="coupon" :style="'background-image: url(' + conpon_bg[goodsQuery.platform] + ')'">
                  <template v-if="item.hasCoupon">{{ item.couponDiscount }}元券</template>
                  <template v-else-if="item.discount">{{ item.discount }}折</template>
                </view>
                <view class="commission">赚{{ token?item.commission:item.diamondCommission }}元</view>
              </view>
              <view class="goods-price">
                {{ item.actualPrice }}
                <view v-if="goodsQuery.platform === 'VOP'" class="discount-text">折后价</view>
              </view>
              <view class="other">
                <view class="original-price">{{ item.originalPrice }}</view>
                <view v-if="goodsQuery.platform !== 'VOP'" class="month-sales">销量{{ item.monthSales }}</view>
              </view>
            </view>
          </view>
        </view>
        <base-list-state :list-length="listLength" :list-query="{ page_no: goodsQuery.pageNum, page_size: goodsQuery.pageSize }" :list-state="listState" :list-empty="listEmpty" />
      </view>
      <search-advice :option="searchObj" @close="closeSearchAdvice" @search="toSearch" />
      <view class="share-icon" :class="{ active: showShareIcon }" @click="showSharePop">
        <image src="/static/images/icon/icon_share_circle.png" mode="aspectFit" />
      </view>
      <share ref="sharePop" :share-option="shareOption" />
    </view>
  </base-page-view>
</template>
<script>
import { mapState } from 'vuex'
import share from '@/components/draw/share'
import searchBar from '@/components/searchBar/index'
import baseSwiper from '@/components/base/base-swiper.vue'
import horizontalList from '@/components/horizontalList/index.vue'
import searchAdvice from './components/searchAdvice/index.vue'
import { debounce } from '@/utils/tools'
import './index.scss'
export default {
  name: 'BHome',
  components: {
    searchBar,
    baseSwiper,
    horizontalList,
    share,
    searchAdvice
  },
  data() {
    return {
      shareBg: `${process.env.VUE_APP_IMAGE_ASSET}/images/share/`,
      bgStyle: `url(${process.env.VUE_APP_IMAGE_ASSET}/images/biHuaSuan/bg_home.png) no-repeat`,
      statusBarHeight: 20,
      screenWidth: 375,
      shareOption: {},
      showShareIcon: true,
      banner_list: [{ pic: `${process.env.VUE_APP_IMAGE_ASSET}/images/biHuaSuan/banner.jpg`, type: 'download' }],
      conpon_bg: {
        PDD: `${process.env.VUE_APP_IMAGE_ASSET}/images/biHuaSuan/bg_coupon_PDD.png`,
        VOP: `${process.env.VUE_APP_IMAGE_ASSET}/images/biHuaSuan/bg_coupon_VOP.png`
      },
      platform_list: [],
      catehory_list: [],
      goods_list: [],
      refreshFlag: false,
      listState: {
        loading: false,
        more: true
      },
      listEmpty: {
        type: 'empty_network',
        text: '暂无数据哦~~'
      },
      goodsQuery: {
        cid: '',
        platform: 'PDD',
        platformName: '拼多多',
        pageNum: 1,
        pageSize: 20
      },
      searchObj: {
        clipData: '',
        show: false
      },
      tabTitle: ''
    }
  },
  computed: {
    ...mapState(['token', 'userInfo']),
    listLength() {
      // 由于微信小程序无法自动更新base-list-state组件,故采用computed
      return this.goods_list.length
    }
  },
  created() {
    uni.getSystemInfo({
      success: ({ statusBarHeight, screenWidth }) => {
        this.statusBarHeight = statusBarHeight
        this.screenWidth = screenWidth
      }
    })
  },
  onLoad() {
    this.fetchData()
  },
  onShow() {
    this.getClipData()
  },
  onHide() {
    this.clearClipData()
  },
  onUnload() {
    this.clearClipData()
  },
  onPageScroll(res) {
    this.showShareIcon = false
    clearInterval(this.shareTimer)
    this.shareTimer = setTimeout(() => {
      this.showShareIcon = true
    }, 500)
  },
  onPullDownRefresh() {
    this.goodsQuery.pageNum = 1
    this.fetchGoodsData(true)
  },
  onReachBottom: debounce(function() {
    if (this.listState.more && !this.listState.loading) {
      this.goodsQuery.pageNum++
      this.fetchGoodsData()
    }
  }, 500),
  methods: {
    toSearchPage() {
      this.$navigateTo('/pagesBHS/search/index')
      // 埋点
      this.$trackSDK.track('bhs.home.search.click')
    },
    toMine() {
      this.$navigateTo('/pagesMine/order/index')
      // 埋点
      this.$trackSDK.track('bhs.home.button.click', '', {
        title: '订单按钮'
      })
    },
    fetchData() {
      // this.fetchBannerData()
      this.fetchPlatformData()
    },
    showSharePop() {
      if (this.token) {
        this.$refs.sharePop.show(this.shareOption)
      } else {
        this.$navigateTo('/pages/login/index')
      }
    },
    async fetchBannerData() {
      const res = await this.$api.biHuaSuanApi.getBanner({
        adType: 'BANNER',
        limit: 10,
        position: 'BANNER_PDD'
      })
      if (res.success) {
        this.banner_list = res.data || []
      }
    },
    async fetchPlatformData() {
      const res = await this.$api.biHuaSuanApi.getSearchPlatform()
      if (res.success && res.data) {
        this.platform_list = res.data
        this.goodsQuery.platform = this.platform_list[0].platform
        this.fetchCategoryData()
      }
    },
    platformChange(item) {
      this.goodsQuery.platform = item.platform
      this.goodsQuery.platformName = item.name
      this.fetchCategoryData()
    },
    async fetchCategoryData() {
      const res = await this.$api.biHuaSuanApi.getCategory({
        platform: this.goodsQuery.platform
      })
      if (res.success) {
        this.catehory_list = res.data || []
        if (this.catehory_list.length) {
          this.goodsQuery.cid = this.catehory_list[0].cid
          this.tabTitle = this.catehory_list[0].title
          this.$refs['category-list'].setIndex(0)
          this.goodsQuery.pageNum = 1
          this.listState.more = true
          this.fetchGoodsData()
        }
      }
    },
    async fetchGoodsData(flag) {
      this.refreshFlag = !!flag
      this.listState.loading = true
      const res = await this.$api.biHuaSuanApi.getGoods(this.goodsQuery)
      if (res.success && res.data) {
        const list = res.data.list || []
        this.goods_list = this.goodsQuery.pageNum === 1 ? list : this.goods_list.concat(list)
        this.listState.more = list.length === this.goodsQuery.pageSize
      }
      setTimeout(() => {
        this.listState.loading = false
        this.refreshFlag = false
        uni.stopPullDownRefresh()
      }, 500)
    },
    getClipData() {
      // #ifndef H5
      uni.getClipboardData({
        success: res => {
          if (res.data && res.data !== ' ') {
            console.log(res.data, 666666)
            this.searchObj = {
              clipData: res.data,
              show: true
            }
          } else {
            this.searchObj.clipData = ''
          }
        }
      })
      // #endif
    },
    clearClipData() {
      // #ifndef H5
      if (this.searchObj.clipData) {
        uni.setClipboardData({
          data: ' ',
          success: () => {
            uni.showToast({ title: '', icon: 'none', duration: 1 })
          },
          fail: res => {
            console.log('fail', res)
          }
        })
      }
      // #endif
    },
    closeSearchAdvice(flag) {
      this.searchObj.show = false
      if (!flag) {
        // 埋点
        this.$sensorTrack('CLICKBUTTON', {
          page_name: 'bargain',
          button_name: 'cancel',
          goods_name: this.searchObj.clipData
        })
      }
    },
    toSearch() {
      // 埋点
      // this.$sensorTrack('CLICKBUTTON', {
      //   page_name: 'bargain',
      //   button_name: 'search',
      //   goods_name: this.searchObj.clipData
      // })
      this.$trackSDK.track('bhs.home.button.click', '', {
        title: '剪贴板搜索按钮'
      })

      uni.setStorage({
        key: 'clipDataSearch',
        data: this.searchObj.clipData,
        success: () => {
          this.closeSearchAdvice(true)
          this.$navigateTo('/pagesBHS/search/index')
        }
      })
    },
    bannerItemClick({ item }) {
      if (item.type === 'download') {
        uni.showToast({ title: '下载碧选APP，领取更多优惠券', icon: 'none' })
      }
    },
    categoryItemClick(index) {
      this.$refs['category-list'].setIndex(index)
      this.goodsQuery.cid = this.catehory_list[index].cid
      this.goodsQuery.pageNum = 1
      this.listState.more = true
      uni.pageScrollTo({
        scrollTop: Math.ceil((296 / 750) * this.screenWidth),
        duration: 300
      })
      this.fetchGoodsData()
      this.tabTitle = this.catehory_list[index].title
      // 埋点
      this.$trackSDK.track('bhs.home.tabs.click', '', {
        title: this.catehory_list[index].title
      })
    },
    toGoods(item) {
      this.$navigateTo(`/pagesBHS/goods/index?goodsId=${item.goodsId}&platform=${item.platform}`)
      // 埋点
      this.$trackSDK.track('bhs.home.list.click', item.goodsId, {
        goods_id: item.goodsId,
        goods_name: item.title,
        platform: item.platform,
        tab_title: this.tabTitle
      })
    },
    back() {
      /* eslint-disable-next-line */
      const pages = getCurrentPages()
      if (pages.length < 2) {
        uni.reLaunch({ url: '/pages/home/index' })
      } else {
        uni.navigateBack()
      }
    },
    initShare() {
      if (this.token) {
        this.shareOption.share_url = ''
        this.shareOption.share_list = [{
            pic: this.shareBg + 'share_01.jpg',
            titleArr: [
              '选择，大于努力',
              '加入碧选',
              '自购分享多赚一点'
            ]
          },
          {
            pic: this.shareBg + 'share_02.jpg',
            titleArr: [
              '选择，大于努力',
              '加入碧选',
              '自购分享多赚一点'
            ]
          },
          {
            pic: this.shareBg + 'share_03.jpg',
            titleArr: [
              '选择，大于努力',
              '加入碧选',
              '自购分享多赚一点'
            ]
          }
        ]
        this.showShare()
      } else {
        this.hideShare()
      }
    }
  }
}
</script>
